/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package basic_image_editor.PointOperations.ChangeHistogram;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;

/**
 *
 * @author gihanchanuka
 */
public class CropImage extends javax.swing.JPanel {

    /**
     * Creates new form CropImage
     */
    private BufferedImage img;
    private BufferedImage cropImg;
    private ImageIcon icon;
    private int x1, y1, x2, y2;

    public CropImage(BufferedImage img) {
        this.img = img;
        initComponents();
        icon = new ImageIcon(img);
        labelCropImage.setIcon(icon);
    }
    public BufferedImage getBufferedImage(ImageIcon imageIcon) {
        Image img = imageIcon.getImage();

        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
// Draw img into bi so we can write it to file.
        g2.drawImage(img, 0, 0, null);
        g2.dispose();
        return bi;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelCropImage = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        labelCropImage = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        textUpper = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        textLower = new javax.swing.JTextField();
        buttonCrop = new javax.swing.JButton();
        buttonReset = new javax.swing.JButton();
        buttonSave = new javax.swing.JButton();
        comboBoxFormat = new javax.swing.JComboBox();

        panelCropImage.setBackground(new java.awt.Color(199, 142, 142));

        labelCropImage.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                labelCropImageMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                labelCropImageMouseEntered(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                labelCropImageMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                labelCropImageMouseReleased(evt);
            }
        });
        labelCropImage.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                labelCropImageMouseDragged(evt);
            }
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                labelCropImageMouseMoved(evt);
            }
        });
        jScrollPane1.setViewportView(labelCropImage);

        javax.swing.GroupLayout panelCropImageLayout = new javax.swing.GroupLayout(panelCropImage);
        panelCropImage.setLayout(panelCropImageLayout);
        panelCropImageLayout.setHorizontalGroup(
            panelCropImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );
        panelCropImageLayout.setVerticalGroup(
            panelCropImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
        );

        jPanel2.setBackground(new java.awt.Color(231, 228, 157));

        jLabel1.setText("Left Upper Corner: ");

        jLabel2.setText("Right Lower Corner : ");

        buttonCrop.setText("Crop");
        buttonCrop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCropActionPerformed(evt);
            }
        });

        buttonReset.setText("Reset");
        buttonReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonResetActionPerformed(evt);
            }
        });

        buttonSave.setText("Save");
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        comboBoxFormat.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "jpg", "png" }));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel1)
                .addGap(4, 4, 4)
                .addComponent(textUpper, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textLower, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(buttonReset, javax.swing.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
                    .addComponent(buttonCrop, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(comboBoxFormat, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(buttonCrop, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonReset, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addGap(4, 4, 4))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(buttonSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(5, 5, 5)
                .addComponent(comboBoxFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(textUpper, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(textLower, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelCropImage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(panelCropImage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void buttonCropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCropActionPerformed

        if (x1 > x2) {
            int temp = x2;
            x2 = x1;
            x1 = temp;
            temp = y2;
            y2 = y1;
            y1 = temp;
        }
        if ((x2 - x1) < img.getWidth() && (y2 - y1) < img.getHeight()) {
        
        this.cropImg = new BufferedImage(x2 - x1, y2 - y1, img.getType());

        for (int i = 0; i < y2 - y1; i++) {
            for (int j = 0; j < x2 - x1; j++) {
                cropImg.setRGB(j, i, img.getRGB(x1 + j, y1 + i));
            }
        }
        this.icon = new ImageIcon(cropImg);
        labelCropImage.removeAll();
        labelCropImage.setIcon(icon);
    }
    }//GEN-LAST:event_buttonCropActionPerformed
    private void buttonResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonResetActionPerformed
        icon = new ImageIcon(img);
        labelCropImage.setIcon(icon);
        textUpper.setText("");
        textLower.setText("");
    }//GEN-LAST:event_buttonResetActionPerformed

    private void labelCropImageMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCropImageMousePressed
        Point m = labelCropImage.getMousePosition();
        x1=m.x;
        y1 = m.y;
        textUpper.setText("X: "+Integer.toString(m.x)+" Y: "+Integer.toString(m.y));
    }//GEN-LAST:event_labelCropImageMousePressed

    private void labelCropImageMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCropImageMouseReleased
        Point m = labelCropImage.getMousePosition();
        x2=m.x;
        y2 = m.y;
        textLower.setText("X: "+Integer.toString(m.x)+" Y: "+Integer.toString(m.y));
    }//GEN-LAST:event_labelCropImageMouseReleased

    private void labelCropImageMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCropImageMouseClicked
        Point m = labelCropImage.getMousePosition();
        textLower.setText("X: "+Integer.toString(m.x)+" Y: "+Integer.toString(m.y));
    }//GEN-LAST:event_labelCropImageMouseClicked

    private void labelCropImageMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCropImageMouseEntered
       
    }//GEN-LAST:event_labelCropImageMouseEntered

    private void labelCropImageMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCropImageMouseMoved
        Point m = labelCropImage.getMousePosition();        
        textUpper.setText("X: "+Integer.toString(m.x)+" Y: "+Integer.toString(m.y));
    }//GEN-LAST:event_labelCropImageMouseMoved

    private void labelCropImageMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCropImageMouseDragged
        Point m = labelCropImage.getMousePosition();       
        textLower.setText("X: "+Integer.toString(m.x)+" Y: "+Integer.toString(m.y));
    }//GEN-LAST:event_labelCropImageMouseDragged

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
        /*
         * Save the filtered image in the selected format. The selected item
         * will be the name of the format to use
         */
        String format = (String) comboBoxFormat.getSelectedItem();
        /*
         * Use the format name to initialise the file suffix. Format names
         * typically correspond to suffixes
         */
        if (cropImg != null) {
            File saveFile = new File("savedimage." + format);
            JFileChooser chooser = new JFileChooser();
            chooser.setSelectedFile(saveFile);
            int rval = chooser.showSaveDialog(comboBoxFormat);
            if (rval == JFileChooser.APPROVE_OPTION) {
                saveFile = chooser.getSelectedFile();
                /*
                 * Write the filtered image in the selected format, to the file
                 * chosen by the user.
                 */
                chooser.setSelectedFile(null);
                try {
                    
                    ImageIO.write(cropImg, format, saveFile);
                } catch (IOException ex) {
                    chooser.setSelectedFile(null);
                }
            }
        }
    }//GEN-LAST:event_buttonSaveActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCrop;
    private javax.swing.JButton buttonReset;
    private javax.swing.JButton buttonSave;
    private javax.swing.JComboBox comboBoxFormat;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelCropImage;
    private javax.swing.JPanel panelCropImage;
    private javax.swing.JTextField textLower;
    private javax.swing.JTextField textUpper;
    // End of variables declaration//GEN-END:variables
}
